package com.dhnsoft.education.service.acl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhnsoft.education.entity.acl.User;
import com.dhnsoft.education.entity.acl.UserRole;
import com.dhnsoft.education.mapper.acl.UserMapper;
import com.dhnsoft.education.service.acl.UserRoleService;
import com.dhnsoft.education.service.acl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public User selectByUsername(String username) {
        return baseMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    //根据用户id和角色id来赋予用户角色权限
    @Override
    public void saveUserRoleRelationShip(String userId,String[] roleIds) {
        //1.首先删除已有的用户所属角色
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id",userId));
        //2.创建空的用户角色集合
        List<UserRole> userRoleList = new ArrayList<>();
        //3.把用户id和角色集合（有可能是一个或者多个）填充
        for (String roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
    }
}
